﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BonsaiScrum.Bus;
using BonsaiScrum.Core.Query;
using BonsaiScrum.Mvc.Models;
using BonsaiScrum.Core.Command;
using BonsaiScrum.Core.Domain.Shared;
using BonsaiScrum.Core.Persistance;
using BonsaiScrum.Mvc.Services;
using BonsaiScrum.Mvc.Filters;
using BonsaiScrum.Core.Domain;

namespace BonsaiScrum.Mvc.Controllers
{
    [Authorize]
    [HandleError]
    public class ProjectController : Controller
    {
        private readonly ICommandBus _commandBus;
        private readonly IProjectReportingRepository _projectReportingRepository;
        private readonly IUserSession _userSession;

        public ProjectController() { }

        public ProjectController(ICommandBus commandBus, IProjectReportingRepository projectReportingRepository, IUserSession userSession)
        {
            _commandBus = commandBus;
            _projectReportingRepository = projectReportingRepository;
            _userSession = userSession;
        }

        // GET: /Project/
        public ActionResult Index()
        {
            var model = _projectReportingRepository.GetAllActiveProjects();
            return View(model);
        }

        [Role(typeof(Manager))]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [Role(typeof(Manager))]
        public ActionResult Create(CreateProjectModel model)
        {
            if (ModelState.IsValid)
            {
                var createProjectCommand = new CreateNewProject(model.ProjectName, model.ProjectDescription, _userSession.CurrentUserId);
                _commandBus.Publish(createProjectCommand);

                return View("CreateProjectSuccess");
            }

            return View(model);
        }

        public ActionResult Dashboard(int id)
        {
            var projectReport = _projectReportingRepository.GetProjectWithId(id);

            if (projectReport == null)
            {
                TempData["Message"] = "Project was not found.";
                return RedirectToAction("Index");
            }

            return View(projectReport);
        }

        [HttpPost]
        public ActionResult Drop(int id)
        {
            var dropProjectCommand = new DropProject(id, 1);
            _commandBus.Publish(dropProjectCommand);

            return View("ProjectHasBeenDropped");
        }

    }
}
